{-# LANGUAGE StrictData #-}
{-# LANGUAGE OverloadedStrings #-}

module RealResult_Module
    ( RealResult (..)
    , Body (..)
    , Head (..)
    , decodeTopLevel
    ) where

import Data.Aeson
import Data.Aeson.Types (emptyObject)
import Data.ByteString.Lazy (ByteString)
import Data.HashMap.Strict (HashMap)
import Data.Text (Text)

{-| 实时成绩

head:
头部数据

body:
主体数据
-}
data RealResult = RealResult
    { headRealResult :: Head
    , bodyRealResult :: Body
    } deriving (Show)

{-| 主体数据

team:
代表队/代表团/俱乐部

athleteName:
运动员姓名

athleteBib:
运动员号码

athleteTelephone:
运动员联系方式

resultA:
A线成绩

resultB:
B线成绩

rank:
排名
-}
data Body = Body
    { teamBody :: Text
    , athleteNameBody :: Text
    , athleteBibBody :: Text
    , athleteTelephoneBody :: Text
    , resultABody :: Text
    , resultBBody :: Text
    , rankBody :: Text
    } deriving (Show)

{-| 头部数据

deviceID:
设备Id

messageUUID:
消息Uuid

timestamp:
发送消息的时间。格式：yyyy-MM-dd HH:mm:ss.fff 比如：2020-09-02 12:24:09.923

messageType:
消息类型
-}
data Head = Head
    { deviceIDHead :: Text
    , messageUUIDHead :: Text
    , timestampHead :: Text
    , messageTypeHead :: Text
    } deriving (Show)

decodeTopLevel :: ByteString -> Maybe RealResult
decodeTopLevel = decode

instance ToJSON RealResult where
    toJSON (RealResult headRealResult bodyRealResult) =
        object
        [ "Head" .= headRealResult
        , "Body" .= bodyRealResult
        ]

instance FromJSON RealResult where
    parseJSON (Object v) = RealResult
        <$> v .: "Head"
        <*> v .: "Body"

instance ToJSON Body where
    toJSON (Body teamBody athleteNameBody athleteBibBody athleteTelephoneBody resultABody resultBBody rankBody) =
        object
        [ "Team" .= teamBody
        , "AthleteName" .= athleteNameBody
        , "AthleteBib" .= athleteBibBody
        , "AthleteTelephone" .= athleteTelephoneBody
        , "ResultA" .= resultABody
        , "ResultB" .= resultBBody
        , "Rank" .= rankBody
        ]

instance FromJSON Body where
    parseJSON (Object v) = Body
        <$> v .: "Team"
        <*> v .: "AthleteName"
        <*> v .: "AthleteBib"
        <*> v .: "AthleteTelephone"
        <*> v .: "ResultA"
        <*> v .: "ResultB"
        <*> v .: "Rank"

instance ToJSON Head where
    toJSON (Head deviceIDHead messageUUIDHead timestampHead messageTypeHead) =
        object
        [ "DeviceId" .= deviceIDHead
        , "MessageUuid" .= messageUUIDHead
        , "Timestamp" .= timestampHead
        , "MessageType" .= messageTypeHead
        ]

instance FromJSON Head where
    parseJSON (Object v) = Head
        <$> v .: "DeviceId"
        <*> v .: "MessageUuid"
        <*> v .: "Timestamp"
        <*> v .: "MessageType"
